#include "check_chat.h"
#include "ui_check_chat.h"
#include "databasemanager.h"
#include "widget.h"

#include <qscrollarea.h>
#include <QVBoxLayout>
#include <QTabWidget>
#include <qlabel.h>
#include <QPushButton>
#include <QMessageBox>

check_chat *check_chat::instance =nullptr;
check_chat::check_chat(QWidget *parent,const QString& username)
    : QWidget(parent)
    , ui(new Ui::check_chat)
    ,username(username)
{
    ui->setupUi(this);


    for (int i = 0; i < 2; ++i) {
        QScrollArea* scrollArea = new QScrollArea(this);
        scrollArea->setWidgetResizable(true);
        scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

        QWidget* pageWidget = new QWidget(this);
        QVBoxLayout* pageLayout = new QVBoxLayout(pageWidget);
        // 这里可以先向pageLayout添加一些初始内容（如果有）
        // 例如：
        // QPushButton* btn = new QPushButton("Button", this);
        // pageLayout->addWidget(btn);

        pageWidget->setLayout(pageLayout);
        scrollArea->setWidget(pageWidget);

        // 将带有滚动区域的页面添加到tabWidget
        QWidget *tmp=ui->tabWidget->widget(i);
        QVBoxLayout *vlayout=new QVBoxLayout(tmp);
        vlayout->addWidget(scrollArea);
        tmp->setLayout(vlayout);
    }

    ui->tabWidget->setCurrentIndex(currentIndex);

    connect(ui->tabWidget,&QTabWidget::currentChanged,[=](int index){
        if(index==0)
        {
            currentIndex=0;
            ui->tabWidget->setCurrentIndex(currentIndex);
            ui->tabWidget->widget(1)->setVisible(false);
            ui->tabWidget->widget(0)->setVisible(true);
            PrivateList();
        }
        else if(index==1)
        {
            currentIndex=1;
            ui->tabWidget->setCurrentIndex(currentIndex);
            ui->tabWidget->widget(0)->setVisible(false);
            ui->tabWidget->widget(1)->setVisible(true);
            GroupList();
        }
    });



}

check_chat::~check_chat()
{
    delete ui;
}

void check_chat::destoryInstance()
{
    if(instance)
    {
        qDebug()<<"delete check_chat";
        delete instance;
        instance=nullptr;
    }
}

check_chat *check_chat::getInstance(QWidget *parent,const QString& username)
{
    if(instance==nullptr)
    {
        instance=new check_chat(parent,username);
    }
    return instance;
}

void check_chat::PrivateList()
{
    // qDebug() << "tabWidget标签页数量:" << ui->tabWidget->count();

    // QWidget *tabPage = ui->tabWidget->widget(1);
    // qDebug() << "标签页1是否存在:" << (tabPage ? "是" : "否");

    // if (tabPage) {
    //     QLayout *tabLayout = tabPage->layout();
    //     qDebug() << "标签页1布局是否存在:" << (tabLayout ? "是" : "否");

    //     if (tabLayout) {
    //         QWidget *firstWidget = tabLayout->itemAt(0)->widget();
    //         qDebug() << "标签页1第一个控件类型:" << firstWidget->metaObject()->className();
    //     }
    // }
    QScrollArea* scrollArea = qobject_cast<QScrollArea*>(ui->tabWidget->widget(0)->layout()->itemAt(0)->widget());
    if(!scrollArea)
    {
        qDebug()<<"未找到";
    }
    std::tuple<QString,QString,QString> tmp=DatabaseManager::getInstance().query_login(this->id);
    QVector<std::tuple<QString,QString,QString>> vec;vec.push_back(tmp);
    if(vec!=private_vec)
    {
        change_private=false;
        private_vec=vec;
        qDebug()<<"Request update";
    }
    if(!change_private)
    {
        change_private=true;
        while (scrollArea->widget()->layout()->count()) {
            QLayoutItem* item = scrollArea->widget()->layout()->takeAt(0);
            if (item) {
                QWidget* widget = item->widget();
                if (widget) {
                    widget->deleteLater();
                }
                delete item;
            }
        }
        QVector<QWidget*> vector;
        int cnt=private_vec.size();
        qDebug()<<"cnt="<<cnt;
        QVector<QPushButton*> vecs;
        for(int i=0;i<cnt;++i)
        {
            QWidget *widget=new QWidget(this);
            widget->setFixedSize(450,100);
            QHBoxLayout *hlayout=new QHBoxLayout(widget);
            QLabel *picture=new QLabel(widget);
            picture->setPixmap(QPixmap(std::get<1>(private_vec[i])));
            picture->setScaledContents(true);//自适应大小
            picture->setFixedSize(100,100);
            hlayout->addWidget(picture);
            QLabel *text_label=new QLabel(QString("%1 %2").arg(this->id).arg(std::get<0>(private_vec[i])),widget);
            hlayout->addWidget(text_label);

            QPushButton* button_1=new QPushButton("聊天");
            connect(button_1,&QPushButton::clicked,[=]{
                DatabaseManager::getInstance().insert_request_or_member(0,0,this->username,this->id,0) ;
                change_private=false;
                return ;
            });
            vecs.push_back(button_1);
            hlayout->addWidget(button_1);

            QVector<std::tuple<QString,QString,QString,int>> res=DatabaseManager::getInstance().query_request(this->username,this->id);
            bool first=res.size();
            res.append(DatabaseManager::getInstance().query_send_request(this->username,this->id));
            if(res.empty()||std::get<3>(res[0])==0)
            {
                qDebug()<<"进入上方";
                QPushButton* button_2=new QPushButton("添加");
                button_2->setFixedSize(100,100);
                connect(button_2,&QPushButton::clicked,[=]{
                    DatabaseManager::getInstance().insert_request_or_member(1,0,this->username,this->id,0) ;
                    return ;
                });        
                hlayout->addWidget(button_2);
            }
            else {
                if(!first){
                    qDebug()<<"进入下1";
                    if(std::get<3>(res[i])==1)
                    {
                        QPushButton* button_3=new QPushButton("同意");
                        QPushButton* button_4=new QPushButton("不同意");
                        // button_2->setFixedSize(100,100);
                        // button_3->setFixedSize(100,100);
                        connect(button_3,&QPushButton::clicked,[=]{
                            DatabaseManager::getInstance().insert_request_or_member(1,0,this->id,this->username,1) ;

                        });
                        connect(button_4,&QPushButton::clicked,[=]{
                            DatabaseManager::getInstance().insert_request_or_member(1,0,this->id,this->username,2) ;
                        });
                        hlayout->addWidget(button_3);
                        hlayout->addWidget(button_4);
                    }
                    else if(std::get<3>(res[i])>1){
                        QLabel *res_label=new QLabel(widget);
                        if(std::get<3>(res[i])==3)
                        {
                            res_label->setText("已不同意");
                        }else res_label->setText("已同意");
                        hlayout->addWidget(res_label);
                    }
                }else{
                    qDebug()<<"进入下2";
                    QLabel *res_label=new QLabel(widget);
                    if(std::get<3>(res[i])==1)
                    {
                        res_label->setText("已申请");
                    }
                    else if(std::get<3>(res[i])!=0){
                        qDebug()<<"res_label="<<std::get<3>(res[i]);
                        if(std::get<3>(res[i])==3)
                        {
                            res_label->setText("对方已不同意");
                        }else if(std::get<3>(res[i])==2)
                            res_label->setText("对方已同意");
                        else res_label->setText("已申请");
                    }
                    hlayout->addWidget(res_label);
                }

            }

            widget->setLayout(hlayout);
            scrollArea->widget()->layout()->addWidget(widget);
            vector.push_back(widget);
            isShow.push_back(false);
        }
        for(int i=0;i<cnt;++i)
        {
            connect(vecs[i],&QToolButton::clicked,[=](){
                if(isShow[i])
                {
                    QMessageBox::warning(this,"警告","该聊天已经打开");
                    return ;
                }
                isShow[i]=true;
                Widget *widget=new Widget(nullptr,this->username,std::get<2>(vec[i]));
                widget->set_basement(this->id,std::get<0>(vec[i]));
                widget->setWindowIcon(QPixmap(std::get<1>(vec[i])));
                widget->setWindowTitle(std::get<0>(vec[i]));
                widget->show();
                //connect第三个参数
                connect(widget,&Widget::closeWidget,this,[=](){
                    isShow[i]=false;
                });
            });
        }
    }
}

void check_chat::GroupList()
{

}

void check_chat::set_username(const QString &username)
{
    this->username=username;
    qDebug()<<"set username="<<this->username;
}






void check_chat::on_toolButton_clicked()
{
    this->id=ui->lineEdit->text();
    if(currentIndex==0)
        PrivateList();
    else GroupList();
}

